import {
  View,
  StyleSheet,
  Pressable,
  ScrollView,
  Text,
  Animated,
  NativeSyntheticEvent,
  NativeScrollEvent,
} from 'react-native'
import SearchTxt from '../../component/searchTxt'
import { common, flexCol } from '../../assets/style/common'
import useGetStatusBar from '../../utils/useGetStatusBar'
import { LinearGradient } from 'expo-linear-gradient'
import MoreMenu from '../../component/moreMenu'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import TabMenus from '../../component/tabMenus/tabMenus'
import GoodCard from '../../component/home/goodCard'
import { GoodsData } from '../../assets/data/data'
import { useFocusEffect } from '@react-navigation/native'
let lastScrollY = 0
let currentMenusHeight = 0

enum SortEnum {
  'synthesize' = 1,
  'saleCount' = 2,
}
export const sortListData = [
  { label: '综合', id: 1 },
  { label: '价格从高到低', id: 2 },
  { label: '价格从低到高', id: 3 },
]
export const curSort = {
  id: 0,
}
export default function GoodSearch({ route, navigation }: any) {
  const scrollY = useRef(new Animated.Value(0)).current
  const [barHeight] = useGetStatusBar()
  const [getMenusHeight, setMenusHeight] = useState(0)
  const [showSort, setShowSort] = useState(false)
  useEffect(() => {
    setMenusHeight(barHeight + 82)
  }, [barHeight])
  const [getCurSort, setCurSort] = useState(1)
  const menusHeight = useMemo(() => {
    const ret = scrollY.interpolate({
      inputRange: [0, 40],
      outputRange: [barHeight + 82, barHeight + 54],
    })
    ret.addListener(value => {
      setMenusHeight(value.value)
    })
    return ret
  }, [barHeight])
  useFocusEffect(
    useCallback(() => {
      curSort.id && setCurSort(curSort.id)
      setShowSort(false)
      curSort.id = 0
    }, []),
  )
  const curSortLable = useMemo(() => {
    return sortListData.find(item => item.id === getCurSort)?.label
  }, [getCurSort])
  const borderRadius = scrollY.interpolate({
    inputRange: [0, 40],
    outputRange: [0, 8],
  })
  const [sortCondition, setConition] = useState(SortEnum.synthesize)
  function goBack() {
    navigation.goBack()
  }
  function onChangeSort(type: SortEnum) {
    if (type === SortEnum.synthesize && sortCondition === type) {
      setShowSort(true)
      navigation.navigate('GoodSearchWrap', {
        screen: 'GoodSearchSort',
        params: JSON.stringify({
          type: getCurSort,
          paddingTop: getMenusHeight - 14 + 32,
        }),
      })
      return
    }
    setConition(type)
  }
  function onShowFilter() {}
  const menus = [
    { label: '全部', key: 'all' },
    { label: '上新', key: 'new' },
    { label: '攻略', key: 'strategy' },
  ]
  function onScroll(e: NativeSyntheticEvent<NativeScrollEvent>) {
    const layoutH = e.nativeEvent.layoutMeasurement.height
    const contentSizeH = e.nativeEvent.contentSize.height
    const y = e.nativeEvent.contentOffset.y
    if (Math.floor(layoutH + y) >= Math.floor(contentSizeH)) return
    if (y <= 0) return
    const dis = (y - lastScrollY) / 4
    if (dis >= 0) {
      // 向上滚
      currentMenusHeight =
        dis + currentMenusHeight < 40 ? dis + currentMenusHeight : 40
    } else {
      // 向下滚
      currentMenusHeight =
        dis + currentMenusHeight > 0 ? dis + currentMenusHeight : 0
    }

    scrollY.setValue(currentMenusHeight)
    lastScrollY = y
  }

  return (
    <View style={[common.flexCol, styles.contain]}>
      <Animated.View
        style={[
          {
            height: menusHeight,
          },
          {
            marginBottom: -14,
          },
        ]}
      >
        <LinearGradient
          start={{ x: 0.2, y: 0.3 }}
          end={{ x: 0.8, y: 0.7 }}
          colors={['#73d7f7', '#57aef0']}
          style={[
            flexCol(styles.searchWrap),
            {
              height: '100%',
              paddingTop: barHeight,
            },
          ]}
        >
          <Pressable onPress={goBack}>
            <Text style={styles.menuSize}>&#xe601;</Text>
          </Pressable>
          <SearchTxt
            showMenu
            initTxtNptValue={route.params.value}
            style={styles.searchTxt}
            placeholderSwiper={false}
            isInput={true}
            placeholder="请输入宝贝"
          />
          <MoreMenu />
          <TabMenus list={menus} initActive={0} isScroll={false} />
        </LinearGradient>
      </Animated.View>

      <Animated.View
        style={[
          common.flexCol,
          styles.condition,
          { borderRadius: borderRadius },
        ]}
      >
        <Pressable
          style={[styles.conditionMenu1, common.flexCol]}
          onPress={() => onChangeSort(SortEnum.synthesize)}
        >
          <Text
            style={[
              styles.conditionTxt,
              sortCondition === SortEnum.synthesize && styles.active,
            ]}
          >
            {curSortLable}
          </Text>
          <Text
            style={[
              styles.nptIcon,
              {
                transform: showSort
                  ? [{ rotateZ: '-90deg' }]
                  : [{ rotateZ: '90deg' }],
                color:
                  sortCondition === SortEnum.synthesize ? '#fb969a' : '#666',
              },
            ]}
          >
            &#xe643;
          </Text>
        </Pressable>
        <Pressable
          style={styles.conditionMenu1}
          onPress={() => onChangeSort(SortEnum.saleCount)}
        >
          <Text
            style={[
              styles.conditionTxt,
              sortCondition === SortEnum.saleCount && styles.active,
            ]}
          >
            销量
          </Text>
        </Pressable>
        <View style={styles.conditionSperate} />
        <Pressable
          style={[styles.conditionMenu2, common.flexCol]}
          onPress={onShowFilter}
        >
          <Text style={styles.conditionTxt}>筛选</Text>
          <Text style={styles.conditionIcon}>&#x10190;</Text>
        </Pressable>
      </Animated.View>

      <View style={styles.scrollWrap}>
        <ScrollView
          scrollEventThrottle={16}
          onScroll={onScroll}
          alwaysBounceVertical={false}
          decelerationRate="fast"
          keyboardDismissMode="on-drag"
          keyboardShouldPersistTaps="handled"
        >
          <View style={[common.flexCol, styles.scrollCnt]}>
            <View style={styles.list}>
              {GoodsData.slice(0, 5).map(item => (
                <GoodCard key={item.id} source={item.cover} {...item} />
              ))}
            </View>
            <View style={styles.sperate} />
            <View style={styles.list}>
              {GoodsData.slice(5).map(item => (
                <GoodCard key={item.id} source={item.cover} {...item} />
              ))}
            </View>
          </View>
        </ScrollView>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  contain: {
    flexDirection: 'column',
    width: '100%',
    height: '100%',
  },
  searchWrap: {
    paddingHorizontal: 12,
    backgroundColor: '#fff',
    flexWrap: 'wrap',
  },
  searchTxt: {
    flex: 1,
    marginLeft: 12,
  },
  menuSize: {
    fontSize: 24,
    fontFamily: 'iconfont',
    color: '#fff',
  },
  scrollWrap: {
    flex: 1,
    backgroundColor: '#f1f1f1',
    width: '100%',
  },
  scrollCnt: {
    paddingLeft: 12,
    paddingTop: 12,
    paddingRight: 12,
    alignItems: 'flex-start',
  },
  condition: {
    width: '100%',
    height: 32,
    borderTopLeftRadius: 6,
    borderTopRightRadius: 6,
    backgroundColor: '#fff',
    paddingRight: 12,
  },
  conditionMenu1: {
    flex: 1,
    justifyContent: 'center',
  },
  active: {
    color: '#fb969a',
  },
  conditionMenu2: {
    marginLeft: 18,
    width: 44,
  },
  conditionSperate: {
    height: 12,
    borderRightWidth: 1,
    borderRightColor: '#eee',
  },
  conditionTxt: {
    color: '#666',
    textAlign: 'center',
  },
  conditionIcon: {
    marginLeft: 4,
    fontSize: 14,
    fontFamily: 'iconfont',
    color: '#666',
  },
  mainMenu: {
    height: 40,
    width: '100%',
    paddingVertical: 8,
    justifyContent: 'space-evenly',
    paddingTop: 10,
    flexWrap: 'wrap',
  },
  menuItem: {
    paddingHorizontal: 24,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 6,
  },
  menusLabel: {
    color: '#fff',
    textAlign: 'center',
  },
  menusLine: {
    height: 3,
    width: 32,
    backgroundColor: '#fed66f',
    borderRadius: 3,
  },
  menusWrap: {
    height: 3,
    width: '100%',
    marginTop: 8,
  },
  list: {
    flex: 1,
  },
  sperate: {
    width: 12,
  },
  nptIcon: {
    fontFamily: 'iconfont',
    fontSize: 12,
    marginLeft: 4,
  },
})
